package com.bwie.es.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Article;
import com.bwie.common.domain.User;
import com.bwie.common.domain.response.ArticleDTO;
import com.bwie.common.result.PageResult;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.es.service.EsService;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
public class EsServiceImpl implements EsService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String INDEX_NAME="article";

    @Override
    public void batch(List<Article> articles) {
        BulkRequest bulkRequest = new BulkRequest();
        try {
            articles.forEach(article -> {
                bulkRequest.add(
                        new IndexRequest(INDEX_NAME)
                                .id(article.getArticleId()+"")
                                .source(JSONObject.toJSONString(article), XContentType.JSON));
            });
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        }catch (Exception e){
            log.info("添加操作异常，异常信息：{}",e);
        }
    }

    @Override
    public PageResult<Article> findEsList(ArticleDTO articleDTO) {
        long total = 0;
        ArrayList<Article> articles = new ArrayList<>();
        try {
            SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            if(StringUtils.isNotBlank(articleDTO.getArticleName())){
                boolQueryBuilder.must(QueryBuilders.matchQuery("articleName",articleDTO.getArticleName()));
            }
            if(articleDTO.getMinDate()!=null){
                boolQueryBuilder.must(QueryBuilders.rangeQuery("articleDate").gte(articleDTO.getMinDate().getTime()));
            }
            if(articleDTO.getMaxDate()!=null){
                boolQueryBuilder.must(QueryBuilders.rangeQuery("articleDate").lte(articleDTO.getMaxDate().getTime()));
            }
            if(articleDTO.getUserId()!=null){
                boolQueryBuilder.must(QueryBuilders.termQuery("userId",articleDTO.getUserId()));
            }
            if(articleDTO.getArticleId()!=null){
                boolQueryBuilder.must(QueryBuilders.termQuery("articleId",articleDTO.getArticleId()));
            }
            searchSourceBuilder.query(boolQueryBuilder);
            searchSourceBuilder.from((articleDTO.getPageNum()-1)*articleDTO.getPageSize());
            searchSourceBuilder.size(articleDTO.getPageSize());
            searchSourceBuilder.sort("articleNum", SortOrder.DESC);
            searchSourceBuilder.highlighter(
                    new HighlightBuilder()
                            .field("articleName")
                            .preTags("<span style=\"color:red\">")
                            .postTags("</span>"));
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchHits = searchResponse.getHits();
            total=searchHits.getTotalHits().value;
            for (SearchHit searchHit : searchHits) {
                String sourceAsString = searchHit.getSourceAsString();
                Article article = JSONObject.parseObject(sourceAsString, Article.class);
                Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
                if(highlightFields!=null){
                    HighlightField highlightField = highlightFields.get("articleName");
                    if(highlightField!=null){
                        Text[] fragments = highlightField.getFragments();
                        StringBuilder sb = new StringBuilder();
                        for (Text fragment : fragments) {
                            sb.append(fragment);
                        }
                        article.setArticleName(sb.toString());
                    }
                }
                articles.add(article);
            }
        }catch (Exception e){

        }
        return PageResult.toPageResult(total,articles);
    }

}
